/*
    Priscilla - A library for enocean network access
    Copyright (C) 2012-2013 B. Aigner / R. Wagner

    This program is free software; you can redistribute it and/or 
    modify it under the terms of the GNU General Public License 
    as published by the Free Software Foundation; either version 2 
    of the License, or at your option any later version. 
 
    This program is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    GNU General Public License for more details. 
 
    You should have received a copy of the GNU General Public License 
    along with this program; if not, write to the Free Software 
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. 
 
    Linking this library statically or dynamically with other modules is 
    making a combined work based on this library. Thus, the terms and 
    conditions of the GNU General Public License cover the whole 
    combination. 
 
    As a special exception, the copyright holders of this library give you 
    permission to link this library with independent modules to produce an 
    executable, regardless of the license terms of these independent 
    modules, and to copy and distribute the resulting executable under terms 
    of your choice, provided that you also meet, for each linked independent 
    module, the terms and conditions of the license of that module. An 
    independent module is a module which is not derived from or based on 
    this library. If you modify this library, you may extend this exception 
    to your version of the library, but you are not obligated to do so. If 
    you do not wish to do so, delete this exception statement from your 
    version. 
*/

package at.technikum_wien.embsys.aat.PriscillaCore.connection;

import java.io.IOException;
import java.io.InputStream;
import org.apache.log4j.Logger;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;


import org.xml.sax.SAXException;

import at.technikum_wien.embsys.aat.PriscillaCore.component.EnoceanComponent;
import at.technikum_wien.embsys.aat.PriscillaCore.enums.TeachInOptions;
import at.technikum_wien.embsys.aat.PriscillaCore.link.EnOceanLinkImpl;
import at.technikum_wien.embsys.aat.PriscillaCore.parsing.EnoceanComponentParser;
import at.technikum_wien.embsys.aat.PriscillaCore.telegram.TelegramESP3;

/**
 * Data receiver thread
 * 
 * This thread is started by the serial connector and is responsible 
 * for receiving raw frames through the serial connection.
 * After a frame is received, it will be parsed
 * 
 * @author R. Wagner
 */
public class SerialDataReceiver extends Thread {
	
	
	public static final String ESP3_SYNC_BYTE = "1010101";
	
	private static final Logger log = Logger.getLogger(SerialDataReceiver.class);

	private InputStream in = null;
//	private byte[] buffer = new byte[1024];
	private TeachInOptions options;
	private List<?> listener;
	
	TelegramESP3 telegramESP3 = new TelegramESP3();

	public SerialDataReceiver(InputStream in, TeachInOptions options, List<?> listener) {
		super();
		this.in = in;
		this.options = options;
		this.listener = listener;
		setDaemon(true); // set Deamon Threat
	}
	
	public SerialDataReceiver(InputStream in, TeachInOptions options) {
		super();
		System.err.println("x");
		this.in = in;
		this.options = options;
		setDaemon(true); // set Deamon Threat
	}
	
	public SerialDataReceiver(InputStream in) {
		super();
		System.err.println("x");
		this.in = in;
		this.options = TeachInOptions.ONE_TIME;
		setDaemon(true); // set Deamon Threat
	}

	@SuppressWarnings("unused")
	public void run() {

		int offsetCounter = 0;
		boolean syncMsgReceived = false;
		EnoceanComponentParser parser = new EnoceanComponentParser(listener, options);
		
		for (;;) {
			try {
				int data = in.read();
//				System.out.println(offsetCounter + " .................................................. " + Integer.toHexString(data));
				
				if (Integer.toBinaryString(data).equals(ESP3_SYNC_BYTE)) {
					syncMsgReceived = true;
				} 
				if (syncMsgReceived) {
					// ------------ H E A D E R -----------------------------------
					if (offsetCounter == 0) {
						telegramESP3.reset();
						telegramESP3.setRawMessage(data, offsetCounter);
						offsetCounter++;
					} else {
						telegramESP3.setRawMessage(data, offsetCounter);
						if (offsetCounter == 1) {
						}
						if (offsetCounter == 2) {
							telegramESP3.setDataLength(data);
						}
						if (offsetCounter == 3) {
							telegramESP3.setOptionalDataLenght(data);
						}
						if (offsetCounter == 4) {
							telegramESP3.setPacketType(data);
						}
						// ------------ C R C 8 H -----------------------------------
						if (offsetCounter == 5) {
//							System.err.println("CRC8H");
						}		
						// ------------ D A T A -----------------------------------
						if ((offsetCounter >= 6) && (offsetCounter < (telegramESP3.getDataLength() + 6))){
//							System.out.println("DATA");
						}		
						// ------------ O P T I O N A L     D A T A -----------------------------------
						if ((offsetCounter >= (telegramESP3.getDataLength() + 6)) && 
								(offsetCounter < (telegramESP3.getDataLength() + telegramESP3.getOptionalDataLenght() + 6))) {
//							System.out.println("OOOOOOOOOOD");
						}	
						// ------------ C R C 8 D -----------------------------------
						if (offsetCounter == (telegramESP3.getDataLength() + telegramESP3.getOptionalDataLenght() + 6)) {
//							System.err.println("CRC8D");
							syncMsgReceived = false;
							offsetCounter = 0;
							
							if(telegramESP3.checkCRC() != 0) {
								System.err.println("CRC error, remaining sum: " + telegramESP3.checkCRC());
								return;
							}
//							System.out.println("Received HexString:      " + bytesToHex(telegramESP3.getRawByteHexMessage()));
							
							try {
								//System.out.println("String: " + telegram.getDataString());
								//System.out.println("Size: " + telegram.getDataLength());
								//System.out.println("Opt Size: " + telegram.getOptionalDataLenght());
								//System.out.println("Type" + telegram.getPacketType());
								log.debug("serial packet received");
								switch(telegramESP3.getPacketType()) {
								case RADIO:
									log.debug("serial packet type <radio>, starting parsing");
									EnoceanComponent enoceanComponent = parser.parseEnoceanData(telegramESP3);
									break;
								case RESPONSE:
									log.debug("serial packet type <response>");
									if(telegramESP3.getDataIntOffset(0) != 0x00) {
										log.info("serial response not OK! " + telegramESP3.getDataIntOffset(0));
									} else {
										if(telegramESP3.getDataLength() == 5) {//quick & dirty -> wird verbessert wenn eine Statemaschine verwendet wird
											log.debug("received response, try to extract sending base ID");
											EnoceanComponent enoceanComponentBaseID = parser.parseEnoceanData(telegramESP3);
										}
									}
									break;
								default:
									log.info("Unimplemented ESP packet type");
									break;
								}
								
							} catch (ParserConfigurationException e) {
								log.error("exception: " + e.getMessage());
							} catch (SAXException e) {
								log.error("exception: " + e.getMessage());
							}
						}		
						// ------------ END -----------------------------------
						if ((offsetCounter > (telegramESP3.getDataLength() + telegramESP3.getOptionalDataLenght() + 6)) && (offsetCounter > 5)) {
							log.info("serial packet error!");
						}	
						if (offsetCounter > 0) offsetCounter++;
					}
					
				}
				

				
				
			} catch (IOException e) {
				log.error("exception: " + e.getMessage());
			}
		}
	}
	public static String bytesToHex(byte[] bytes) {
	    final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	    char[] hexChars = new char[bytes.length * 2];
	    int v;
	    for ( int j = 0; j < bytes.length; j++ ) {
	        v = bytes[j] & 0xFF;
	        hexChars[j * 2] = hexArray[v >>> 4];
	        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
	    }
	    return new String(hexChars);
	}
}
